
#include <QSettings>
#include <QFile>
#include "common.h"
#include "config.h"
#include "msgprint.h"

Config *Config::s_pConfig = NULL;

QStringList Config::s_lanList;

Config *Config::instance()
{
    if (s_pConfig==NULL){
        s_pConfig = new Config(CONFIG_FILE);
    }
    return s_pConfig;
}

const QStringList Config::lanList()
{
    if (s_lanList.count()==0){
        // should keep the same order as Config::lanType
        s_lanList << tr("English") << tr("Chinese(GB2312)");
    }
    return s_lanList;
}

Config::Config(const QString &file, QObject *parent) :
    QObject(parent), m_configFile(file)
{
    m_settings = new QSettings(m_configFile, QSettings::IniFormat, this);
}

Config::~Config()
{
    delete m_settings;
    if (s_pConfig){
        s_pConfig = NULL;
    }
}

int Config::getIntValue(configItem key)
{
    return readValue(key).toInt();
}

QString Config::getStringValue(configItem key)
{
    return readValue(key).toString();
}

QVariant Config::readValue(configItem key)
{
    QString keystring = getKeyString(key);
    QVariant value;
    switch (key){
    case SYS_LANGUAGE:{
            value = m_settings->value(keystring, Config::LAN_EN);
            break;
        }
    default:{
            value = m_settings->value(keystring);
            break;
        }
    }
    return value;
}

void Config::setIntValue(configItem key, int value)
{
    if (getIntValue(key)!=value){
        QString keystring = getKeyString(key);
        m_settings->setValue(keystring, value);
        m_settings->sync();
    }
}

void Config::setStringValue(configItem key, QString & value)
{
    if (getStringValue(key)!=value){
        QString keystring = getKeyString(key);
        m_settings->setValue(keystring, value);
        m_settings->sync();
    }
}

QString Config::getKeyString(configItem item)
{
    QString key = "";
    switch(item){
    case SYS_LANGUAGE:{
            key = "common/language";
            break;
        }
    default:{
            ERRR() << "invalid config item" << item;
        }
    }
    return key;
}
